<?php

namespace app\api\model;

class Member extends Base
{
    /**
     * User: setPasswordAttr
     * Notes:保存或修改时自动修改密码为MD5
     * @param $value
     * @return string
     */

    public function setPasswordAttr($value):string
    {
        return MD5($value);
    }

    /**
     * User: login
     * Notes:
     * @param  array post登录数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function login($data)
    {
        $validate = new \app\api\validate\Member;
        if (!$validate->scene('login')->check($data)) {
            return ['code' => 0, 'msg' => $validate->getError()];
        }
        $UserData = $this->where('user', $data['user'])->find();
        if (empty($UserData)) {
            return ['code' => 0, 'msg' => '账号不存在'];
        }
        if ($UserData['juge'] == 1) {
            return ['code' => 0, 'msg' => '您账号已被管理员禁用'];
        }
        if ($UserData['password'] == md5($data['password'])) {
            session('admin.id', $UserData['id']);
            session('admin.user', $UserData['user']);
            return ['code' => 1, 'msg' => '登录成功', 'data' => '', 'url' => (String)Url('api/index/index')];
        } else {
            return ['code' => 0, 'msg' => '密码错误'];
        }
    }

    public function register($data)
    {
        $validate = new \app\api\validate\Member;
        if (!$validate->scene('register')->check($data)) {
            return ['code' => 0, 'msg' => $validate->getError()];
        }
        //写入数据库返回用户数据
        $user = $this->create($data);
        if ($user) {
            session('admin.user', $user['user']);
            session('admin.id', $user['id']);
            return ['code' => 1, 'msg' => '注册成功', 'url' => (String)Url('api/index/index')];
        } else {
            return ['code' => 0, 'msg' => $this->getError()];
        }
    }


}